﻿using Qy.Core;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class ConfigParmService : QyRepository<ConfigParm>
{
    public ConfigParmService(ApplicationContext applicationContext) : base( applicationContext)
    {
    }
    /// <summary>
    ///  全部列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<ConfigParm>> GetListAllAsync()
    {
        return await GetAllListAsync("Id desc");
    }
    /// <summary>
    /// 分页列表
    /// </summary>
    public async Task<PagedInfo<ConfigParm>> GetPageListAsync(QueryConfigParm parm)
    {
        return await Queryable()
            .WhereIF(!string.IsNullOrEmpty(parm.Name), (data) => data.Name.Contains(parm.Name))
            .WhereIF(!string.IsNullOrEmpty(parm.Code), (data) => data.Code.Contains(parm.Code))
            .OrderBy((data) => data.Id, OrderByType.Desc)
            .ToPageAsync(parm);
    }
    public async Task<bool> GetByCodeAsync(string code)
    {
        List<ConfigParm> configParms = await GetListAllAsync();
        return configParms.FirstOrDefault(o => o.Code == code)?.Value == null;
    }
    public virtual async Task<object> InsertDelCache(ConfigParm configParm)
    {
        if (!await GetByCodeAsync(configParm.Code)) return null;
        return await InsertAndDelCacheAsync(configParm);
    }
    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="editConfigParm"></param>
    /// <returns></returns>
    public async Task<int> UpdateDelCache(ConfigParm editConfigParm)
    {
        ConfigParm configParm = await GetIdAsync(editConfigParm.Id);
        if (configParm == null) return 0;
        if (configParm.Code != editConfigParm.Code && await GetByCodeAsync(editConfigParm.Code) == false)
            return -2;//判断代码是否重复
        configParm.Type = editConfigParm.Type;
        configParm.Code = editConfigParm.Code;
        configParm.Name = editConfigParm.Name;
        configParm.Value = editConfigParm.Value;
        configParm.Remark = editConfigParm.Remark;
        configParm.Status = editConfigParm.Status;
        return await UpdateAndDelCacheAsync(configParm);
    }
    /// <summary>
    /// 调用指定一条
    /// </summary>
    /// <param name="code"></param>
    /// <returns></returns>
    public async Task<string> GetOneAsync(string code)
    {
        List<ConfigParm> configParms = await GetListAllAsync();
        return configParms.FirstOrDefault(o => o.Code == code && o.Status == true)?.Value;
    }

}
